package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter("/*")
@Component
@Order(1)
public class LoginFilter implements Filter {
     private AntPathMatcher antPathMatcher= new AntPathMatcher();
    @Override
    public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) throws IOException, ServletException {
        HttpServletRequest httpServletRequest= (HttpServletRequest) servletRequest;
        //登陆相关的请求都应该放行
        String requestURI = httpServletRequest.getRequestURI();
        String [] patterns=new String[]{"/backend/**","/front/**","/employee/login","/employee/logout",
                "/user/login","/user/sendMsg"};
        for (String pattern : patterns) {
            boolean match = antPathMatcher.match(pattern, requestURI);
            if (match){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }
     /*   antPathMatcher.match("/backend/**",requestURI);
        antPathMatcher.match("/front/**",requestURI);
        antPathMatcher.match("/employee/login",requestURI);
        antPathMatcher.match("/employee/logout",requestURI);*/
        //判断用户是否登陆过,如果登陆了,放行
        //判断的依据
        Employee loginUser = (Employee) httpServletRequest.getSession().getAttribute("loginUser");
        if (loginUser!=null){
            UserHolder.set(loginUser.getId());
            filterChain.doFilter(servletRequest,servletResponse);
            UserHolder.remove();
            return;
        }
        User loginPhone = (User) httpServletRequest.getSession().getAttribute("loginPhone");
        if (loginPhone!=null){
            UserHolder.set(loginPhone.getId());
            filterChain.doFilter(servletRequest,servletResponse);
            UserHolder.remove();
            return;
        }
        //如果没有登录 ,拦截
        //返回数据 R code:0,data:null;msg:NOTLOGIN;
        R r = R.error("NOTLOGIN");
        String jsonString = JSON.toJSONString(r);
        servletResponse.getWriter().write(jsonString);
    }
}
